package com.westcom.vulb.activity;

import java.util.ArrayList;
import java.util.HashMap;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.westcom.vulb.logic.BasicLogic;
import com.westcom.vulb.logic.SessionManager;
import com.westcom.vulb.logic.account;
import com.westcom.vulb.logic.card;
import com.westcom.vulb.logic.comment;
import com.westcom.vulb.protocal.http.Request;
import com.westcom.vulb.protocal.http.Response;
import com.westcom.vulb.util.MyLog;

public class CardGoodFragment extends CardInfoBasicFragment {
    private ListView mListView;
    private ViewerAdapter mAdatper;
    private LoadGoodTask mDataLoader;
    private ValuatCardTask mGooder;
    private ArrayList<User> mGoodList = null;
    private SessionManager sm = null;
    
    @Override
    public void onAttach(Activity activity) 
    {
        super.onAttach(activity);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) 
    {
        View v = inflater.inflate(R.layout.card_good, container, false);
        
        mListView = (ListView) v.findViewById(R.id.card_good_list);
        
        mAdatper = new ViewerAdapter(getActivity(), R.layout.user_list, mGoodList);
        mListView.setAdapter(mAdatper);
        
        if (mLoadingDialog == null) {
            mLoadingDialog = new ProgressDialog(getActivity());
        }
        
        return v;
    }
    
    @Override
    public void onResume() 
    {
        // TODO Auto-generated method stub
        super.onResume();
        sm = SessionManager.getInstance();
        if (mGoodList == null) 
        {
            loadData();
        }else
        {
        	mAdatper.setData(mGoodList);
        }
    }

    @Override
    public void onPause() {
        // TODO Auto-generated method stub
        super.onPause();
    }
    
    @Override
    public void onPrepareOptionsMenu(Menu menu) {
        // TODO Auto-generated method stub
        super.onPrepareOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // TODO Auto-generated method stub
        return super.onOptionsItemSelected(item);
    }
    
    @Override
    public void onCardDetailLoaded() 
    {
    }
    
    private void loadData() 
    {
    	if(mDataLoader == null)
    	{
    		if(null == mGoodList)
        	{
        		mGoodList = new ArrayList<User>();
        	}else
        	{
        		mGoodList.clear();
        	}
    		mLoadingDialog.show();
    		mDataLoader = new LoadGoodTask();
            mDataLoader.execute(new Integer[]{selfActivity().mCardId});
    	}
    }
    
    @Override
    public void onLogoLoaded(Integer uid, Bitmap logo) 
    {
    }

    private class ViewerAdapter extends BaseAdapter 
    {
        private Context mContext;
        private int mLayoutId;
        private ArrayList<User> mData;
        private LayoutInflater mInflater;
        
        private Bitmap mDefaultLogo;
        
        public ViewerAdapter(Context ctx, int layoutId, ArrayList<User> mGoodList) {
            mContext = ctx;
            mLayoutId = layoutId;
            mData = mGoodList;
            
            mInflater = (LayoutInflater) ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }
        
        @Override
        public int getCount() {
            if (mData == null) {
                return 0;
            }
            return mData.size();
        }
        
        public void setData(ArrayList<User> mData) {
            this.mData = mData;
            notifyDataSetChanged();
        }

        @Override
        public Object getItem(int position) {
            if (mData == null) {
                return null;
            }
            return mData.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View v = convertView;
            if (v == null) {
                v = mInflater.inflate(mLayoutId, parent, false);
            }
            
            if (mDefaultLogo == null) {
                mDefaultLogo = BitmapFactory.decodeResource(getResources(), R.drawable.sharemember_tab_normal);
            }
            
            User user = (User) getItem(position);
            TextView tv = (TextView) v.findViewById(R.id.user_name);
            tv.setText(user.userName);
            
            ImageView iv = (ImageView) v.findViewById(R.id.user_logo);
            user.v = iv;
            Bitmap bmp = user.img;
            if (bmp != null && user.v != null) 
            {
            	iv.setImageBitmap(bmp);
            }else
            {
            	LoadProfileImg loadImg = new LoadProfileImg();
            	loadImg.equals(new Integer[]{user.userId});
            }
            return v;
        }
    }
    
    class LoadGoodTask extends AsyncTask<Integer, Integer, String> {
        @Override
        protected String doInBackground(Integer... params) 
        {
        	int cardId = params[0];
            card c = card.getInstanse();
            Response res = c.GetCardGoodUserList(sm.getCurrSessionId(),cardId);
            if(res.errno != Response.SUCCESS)
            {
            	return res.errmsg;
            }
            HashMap<String, Object> map = res.data;
            JSONArray users = (JSONArray)map.get("users");
            mGoodList = new ArrayList<CardGoodFragment.User>();
            for (int i = 0;i<users.length();i++) 
            {
                User user = null;
				try 
				{
					user = new User(users.getJSONObject(i));
				} catch (JSONException e) 
				{
					// TODO Auto-generated catch block
					e.printStackTrace();
					continue;
				}
                res = sm.getCurrentSession().getProfileImage(true, user.userId);
                if(res.errno == Response.SUCCESS)
                {
                	String bitmap_str = (String) res.data.get("personImg");
                	user.img = account.Base64Str2Bitmap(bitmap_str);
                }
                mGoodList.add(user);
            }
            return null;
        }
        @Override
        protected void onCancelled() 
        {
            super.onCancelled();
            if(mLoadingDialog.isShowing())
        	{
        		mLoadingDialog.hide();
        	}
            mDataLoader = null;
        }
        @Override
        protected void onPostExecute(String result) 
        {
            super.onPostExecute(result);
            MyLog.d("GoodList: onPostExecute");
            if(mLoadingDialog.isShowing())
        	{
        		mLoadingDialog.hide();
        	}
            mDataLoader = null;
            if(result != null)
            {
            	selfActivity().launchToast(result);
            	return;
            }
            setGoodButtonImg();
            mAdatper.setData(mGoodList);
        }
    }
    
    class LoadProfileImg extends AsyncTask<Integer, Integer, String> 
    {
    	private int userId;
        @Override
        protected String doInBackground(Integer... params) 
        {
        	userId = params[0];
        	int index = getUserById(userId);
        	if(index <0)
        	{
        		return selfActivity().getResources().getString(R.string.load_profile_img_error);
        	}
        	User u = mGoodList.get(index);
            Response res = res = sm.getCurrentSession().getProfileImage(true,userId);
            if(res.errno != Response.SUCCESS)
            {
            	return res.errmsg;
            }
            String bitmap_str = (String) res.data.get("personImg");
        	u.img = account.Base64Str2Bitmap(bitmap_str);
            return null;
        }
        @Override
        protected void onPostExecute(String result) 
        {
            super.onPostExecute(result);
            MyLog.d("GoodList: onPostExecute");
            if(result != null)
            {
            	selfActivity().launchToast(result);
            	return;
            }
            int index = getUserById(userId);
        	User u = mGoodList.get(index);
        	if(u.v != null && null != u.img)
        	{
        		u.v.setImageBitmap(u.img);
        	}
        }
    }
    
	class ValuatCardTask extends AsyncTask<Integer, Integer, String> {
        @Override
        protected String doInBackground(Integer... params) 
        {
        	int cardId = params[0];
        	int valuation = params[1];
        	mLoadingDialog.show();
        	card c = card.getInstanse();
            Response res = c.Valuat(sm.getCurrSessionId(),cardId,valuation);
        	if(res.errno != Response.SUCCESS)
        	{
        		return res.errmsg;
        	}
            return null;
        }
        @Override
        protected void onPostExecute(String result) 
        {
            super.onPostExecute(result);
            MyLog.d("GoodList: onPostExecute");
            if(mLoadingDialog.isShowing())
        	{
        		mLoadingDialog.hide();
        	}
            mGooder = null;
            if(result != null)
            {
            	selfActivity().launchToast(result);
            	return;
            }
            loadData();
            
        }
    }
	public void valuatCard(int cardId)
	{
		if(null == mGooder)
		{
			
			int valuation = -1;
			if(getUserById(sm.getCurrUid())>=0)
			{
				valuation = 0;
			}else
			{
				valuation = 1;
			}
			mLoadingDialog.show();
			mGooder = new ValuatCardTask();
			mGooder.execute(new Integer[]{cardId,valuation});
		}
	}
    
    public class User 
    {
        public int userId;
        public String userName;
        
        public Bitmap img;
        public ImageView v;
        
        public User(JSONObject data) 
        {
            try 
            {
				this.userId = data.getInt("userId");
				this.userName = data.getString("userName");
			} catch (JSONException e) 
			{
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
        }
    }
    public int getUserById(int userId)
    {
    	int index = -1;
    	User u = null;
    	for(int i = 0;i<mGoodList.size();i++)
    	{
    		u = mGoodList.get(i);
    		if(u.userId == userId)
    		{
    			index = i;
    		}
    	}
    	return index;
    }
    private void setGoodButtonImg()
    {
    	boolean isFound = false;
    	for(User u:mGoodList)
    	{
    		if(u.userId == sm.getCurrUid())
    		{
    			isFound = true;
    			break;
    			
    		}
    	}
    	if(isFound)
    	{
    		selfActivity().setGoodButtonImg(R.drawable.icon_good_selected);
    	}else
    	{
    		selfActivity().setGoodButtonImg(R.drawable.icon_good_normal);
    	}
    }
}
